package cn.tan.json;
import cn.tan.database.jdbc.DBUtil;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.util.stream.Collectors;

@WebServlet(urlPatterns = {"/json"})
public class JsonServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        /* 创建一个简单的Person对象,用作演示
       // StudentDTO personDTO = new StudentDTO("2003066", "黎志雄", "老师",
         //       "网络空间安全学院", "lizhx@dgut.edu.cn", 38, LocalDate.of(2019, 3, 15), BigDecimal.valueOf(1000));

        // 要获取对象的JSON表示，我们需要使用JsonbBuilder类及其toJson（）方法。
        Jsonb jsonb = JsonbBuilder.create();
        String jsonPerson = jsonb.toJson(personDTO);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        resp.getWriter().println(jsonPerson);*/
    }


    // 获取前端post提交的json字符串，并转换为对象；再把对象转为json字符串，生成响应返回前端。
    // curl -v -H "Content-Type: application/json" http://localhost:8080/webapp-demo/json -X POST --data '{"姓名":"黎志雄","工号":"2003066","注册日期":"15-03-2019","薪水":"1000.0","身份":"老师","邮件":"lizhx@dgut.edu.cn","部门":"网络空间安全 学院"}'
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Jsonb jsonb = JsonbBuilder.create();
        String postJsonString = new BufferedReader(new InputStreamReader(req.getInputStream()))
                .lines().collect(Collectors.joining(System.lineSeparator()));

        // 利用jsonb把json字符串转换为对象
        StudentDTO studentDTO = jsonb.fromJson(postJsonString, StudentDTO.class);

        System.out.println(studentDTO.toString());
        int id = studentDTO.getId();
        String name = studentDTO.getName();
        String email = studentDTO.getEmail();
        int phone = studentDTO.getPhone();
        int sex = studentDTO.getSex();

        try {
            Connection conn = DBUtil.getConnection();
            Statement stmt = conn.createStatement();

            stmt.executeUpdate(
                    "CREATE TABLE IF NOT EXISTS `student` (" +
                            "  `id` int(11) unsigned NOT NULL AUTO_INCREMENT," +
                            "  `name` varchar(100) NOT NULL," +
                            "  `email` varchar(100) NOT NULL," +
                            "  `age` int(11) NOT NULL," +
                            "  `sex` int(11) NOT NULL," +
                            "  PRIMARY KEY (`id`)" +
                            ");"
            );

            stmt.executeUpdate(
                    "insert into `student` (`id`,`name`,`email`,`phone`,`sex`) values ( "+
                            id+ "," + name + "," + email + "," + phone + "," + sex + ")"
            );

            ResultSet rs = stmt.executeQuery("select * from student");//选择import java.sql.ResultSet;

            // 遍历每行记录
            while (rs.next()) {
                //如果结果集中有数据，就会循环打印出来
                System.out.println(rs.getString("id") + ","
                        + rs.getString("name") + ","
                        + rs.getString("email")+ ","
                        + rs.getInt("phone")+ ","
                        + rs.getInt("sex")+ ","
                );
                System.out.println("操作成功");
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }



        /*
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 把获取的字符串原样返回
        String jsonStudent = jsonb.toJson(studentDTO);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        resp.getWriter().println(jsonStudent);*/
    }
}
